package com.csw.mybatisSpringboot.config.quanXian;

import com.csw.mybatisSpringboot.config.exception.BusinessException;
import com.csw.mybatisSpringboot.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SignatureException;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;

public class JwtUtil {
    static String key = "644e1d5ca6de601d45e9a25b670e65f1";
    static int seconds = 1 * 60 * 60;

    /**
     * @param id
     * @param subject
     * @param roles
     * @param key
     * @param seconds
     * @return
     */
    public static String createjwt(User user) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().
                setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key).
                claim("user", user);
        if (StringUtils.isNotEmpty(seconds + "")) {
            //builder.setExpiration(new Date(nowMillis + seconds * 1000));
        }
        return builder.compact();
    }

    /**
     * public static User getUserInfo() {
     * HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
     * String token = request.getHeader(TokenConstants.AUTHENTICATION).replaceAll(TokenConstants.PREFIX, "");
     * Object o = JwtUtil.parsejwt(token).get("user");
     * User user = BeanUtil.copyProperties(o, User.class);
     * return user;
     * }
     *
     * @param token
     * @return
     */
    public static Claims parsejwt(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
            System.out.println("id]" + claims.getId());
            System.out.println("账号】" + claims.getSubject());
            System.out.println("签发时间】" + claims.getIssuedAt());
            System.out.println("角色】" + claims.get("user"));
        } catch (ExpiredJwtException e) {
            System.out.println("认证失效");
            throw new BusinessException("认证失效");
        } catch (SignatureException e) {
            System.out.println("签名失效");
            throw new BusinessException("签名失效");
        }
        return claims;
    }

}
